/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.check.checkers;

import cn.ac.iie.di.ban.news.server.check.CheckResult;
import cn.ac.iie.di.ban.news.server.check.Checker;
import cn.ac.iie.di.ban.news.server.util.MD5Pool;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 *
 * @author zwlin
 */
public class MD5Checker implements Checker<String, String> {

    MD5Pool pool;

    public MD5Checker() {
        pool = MD5Pool.getInstance();
    }

    @Override
    public CheckResult check(String src, String target) {
        if (src == null || (src = src.trim()).isEmpty()) {
            return new CheckResult();
        }
        LinkedList<Character> list = new LinkedList<>();
        for (char c : target.toCharArray()) {
            list.add(c);
        }
        try {
            MessageDigest md = pool.Borrow();
            try {
                byte[] bs = md.digest(src.getBytes("utf-8"));
                int i;
                StringBuilder sb = new StringBuilder();
                for (byte b : bs) {
                    i = b & 0x00ff;
                    if (i < 16) {
                        sb.append('0');
                    }
                    sb.append(Integer.toHexString(i));
                }
                for (char a : sb.toString().toCharArray()) {
                    if (a != list.pop()) {
                        return new CheckResult("MD5 of content error.need: " + sb.toString() + " ,given: " + target);
                    }
                }
                return new CheckResult();
            } catch (UnsupportedEncodingException ex) {
                return new CheckResult("unknow error. " + ExceptionUtils.getStackTrace(ex));
            } finally {
                if (md == null) {
                    pool.Return(md);
                }
            }
        } catch (NoSuchAlgorithmException ex) {
            return new CheckResult("MD5 checker error. " + ExceptionUtils.getStackTrace(ex));
        }
    }

}
